package com.lb.activity.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lb.activity.mapper.StationMapper;
import com.lb.activity.mapper.UserMapper;
import com.lb.activity.po.Station;
import com.lb.activity.po.User;
import com.lb.activity.service.UserService;
import com.lb.activity.util.ResultUtil;
import com.lb.activity.util.SnowflakeIdWorker;
import com.lb.activity.util.emumdata.DataEnum;
import com.lb.activity.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author liubin
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private SnowflakeIdWorker idWorker;

    @Override
    public ResultUtil  list(UserVo userVo) {
        PageHelper.startPage(userVo.getPage(),userVo.getLimit());
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status",DataEnum.DELETE_STATUS.getStatus());
        if(userVo.getDeptId() != null){
            criteria.andEqualTo("groupId",userVo.getDeptId());
        }
        List<User> users = userMapper.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return ResultUtil.build(0, "", Integer.parseInt(String.valueOf(pageInfo.getTotal())), pageInfo.getList());
    }

    @Override
    public ResultUtil add(User user) {
        // 查询该用户是否在数据库添加过
        User userByUserName = userMapper.getUserByUserName(user.getUserName());
        if(userByUserName != null){
            return ResultUtil.build(400,"该用户名称已添加");
        }
        // 判断该部门是否有领导
        if(user.getIsLeader() == 1){
            //查询 user 表 ，是否存在leader 是 1的记录
            User userByDeptId = userMapper.getUserByDeptId(user.getGroupId());
            if(userByDeptId != null){
                return ResultUtil.build(400,"该部门已经有领导");
            }
        }
        //随机生成密钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        //加密为16进制表示
        String encryptHex = aes.encryptHex(user.getPassword());
        //封装对象
        user.setId(idWorker.nextId());
        user.setSalt(key);
        user.setStatus(DataEnum.INSERT_STATUS.getStatus());
        user.setPassword(encryptHex);
        //执行插入
        userMapper.insertSelective(user);
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil update(User user) {
        // 判断该部门是否有领导
        if(user.getIsLeader() == 1){
            //查询 user 表 ，是否存在leader 是 1的记录
            User userByDeptId = userMapper.getUserByDeptId(user.getGroupId());
            // 部门领导不为空 并且不是本人
            if(userByDeptId != null && !userByDeptId.getId().equals(user.getId())){
                return ResultUtil.build(400,"该部门已经有领导");
            }
        }
        //执行更新
        userMapper.updateByPrimaryKeySelective(user);
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil delete(Long id) {
        //将状态置为删除状态
        User user = User.builder().id(id).status(DataEnum.DELETE_STATUS.getStatus()).build();
        //执行更新
        userMapper.updateByPrimaryKeySelective(user);
        return ResultUtil.ok();
    }

    @Override
    public User userLogin(String userName, String password) {
        // 将密码加密比对
        User userLogin = userMapper.getUserByUserName(userName);
        if(userLogin != null){
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, userLogin.getSalt());
            //将前端传递的密码  与盐加密后进行比对
            String encryptHex = aes.encryptHex(password);
            if(!encryptHex.equals(userLogin.getPassword())){
                return null;
            }
            return userLogin;
        }
        return null;
    }

    @Override
    public ResultUtil changeStatus(Long id,boolean boolStatus) {
        Long status = DataEnum.INSERT_STATUS.getStatus();
        // 如果为true ,为 lock 即 禁用
        if(boolStatus){
            status = DataEnum.FORBIDDEN_STATUS.getStatus();
        }
        User user = User.builder().id(id).status(status).build();
        userMapper.updateByPrimaryKeySelective(user);
        return ResultUtil.ok();
    }

    @Override
    public UserVo getOneById(Long userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        List<Station> list = stationMapper.list(user.getGroupId(), DataEnum.INSERT_STATUS.getStatus());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        userVo.setStations(list);
        return userVo;
    }

    @Override
    public User getAdminUserByLoginName(String uname) {
        return userMapper.selectByUserLoginName(uname);
    }
}
